const express = require("express");
const pool = require("../pool.js");

const orderRouter = express.Router();
module.exports = orderRouter;

// 查询所有订单
orderRouter.get("/findAll", (req, res, next) => {
  var page = req.query.page || 1;
  const pagesize = 10;
  var offset = (page - 1) * pagesize;
  var sql = "select count(oid) as count from `order`";
  pool.query(sql, (err, r) => {
    if (err) {
      next(err);
      return;
    }
    let pagecount = Math.ceil(r[0].count / pagesize);
    var sql = "select * from `order` limit ?,?";
    pool.query(sql, [offset, pagesize], (err, r) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, data: r, pagecount });
    });
  });
});
// 查询指定用户的订单
orderRouter.get("/find", (req, res, next) => {
  var page = req.query.page || 1;
  let token = req.header("authorization");
  let uid;
  verify(token, (msg) => (uid = msg.uid));
  const pagesize = 10;
  var offset = (page - 1) * pagesize;
  var sql = "select count(oid) as count from `order` where uid=?";
  pool.query(sql, [uid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    let pagecount = Math.ceil(r[0].count / pagesize);
    var sql = "select * from `order` where uid=? limit ?,?";
    pool.query(sql, [uid, offset, pagesize], (err, r) => {
      if (err) {
        next(err);
        return;
      }
      if (r.length != 0) {
        res.send({ code: 200, data: r, pagecount });
      } else {
        res.send({ code: 201, msg: "无订单数据" });
      }
    });
  });
});
// 新增订单
orderRouter.post("/insert", (req, res, next) => {
  var uid = req.body.uid;
  var pname = req.body.pname;
  var ocount = req.body.ocount;
  var ostate = req.body.ostate || "未付款";
  var otime = req.body.otime;
  var oprice = req.body.oprice;
  var oaddress = req.body.oaddress;
  var oname = req.body.oname;
  var ophone = req.body.ophone;
  if (
    uid == "" ||
    uid == undefined ||
    pname == "" ||
    pname == undefined ||
    ocount == "" ||
    ocount == undefined ||
    otime == "" ||
    otime == undefined ||
    oprice == undefined ||
    oprice == "" ||
    oaddress == undefined ||
    oaddress == "" ||
    oname == undefined ||
    oname == "" ||
    ophone == "" ||
    ophone == undefined
  ) {
    res.send({ code: 202, msg: "输入不能为空" });
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(ophone)) {
    res.send({ code: 203, msg: "手机号格式不正确" });
    return;
  }
  var sql = `select sid from supply where sname=?`;
  pool.query(sql, [pname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      sql =
        "insert into `order` values(replace(UUID(),'-',''),?,?,?,?,?,?,?,?,?)";
      pool.query(
        sql,
        [uid, pname, ocount, ostate, otime, oprice, oaddress, oname, ophone],
        (err, r) => {
          if (err) {
            next(err);
            return;
          }
          if (r.affectedRows) {
            // 如果下单成功，相应的库存也得减少
            sql = `update supply set sstore=sstore-? where sname=?`;
            pool.query(sql, [ocount, pname], (err, r) => {
              if (err) {
                next(err);
                return;
              }
              res.send({ code: 200, msg: "插入成功" });
            });
          } else {
            res.send({ code: 201, msg: "插入失败" });
          }
        }
      );
    } else {
      res.send({ code: 204, msg: "商品不存在" });
    }
  });
});
// 根据用户名和时间删除订单
orderRouter.delete("/deleteByName", (req, res, next) => {
  var uname = req.query.uname;
  var otime = req.query.otime;
  if (uname == "" || uname == undefined || otime == "" || otime == undefined) {
    res.send({ code: 202, msg: "输入不可为空" });
    return;
  }
  var sql = "delete from `order` where uname=? and otime=?";
  pool.query(sql, [uname, otime], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r.affectedRows) {
      res.send({ code: 201, msg: "删除失败" });
    } else {
      res.send({ code: 200, msg: "删除成功" });
    }
  });
});
// 根据订单id删除订单
orderRouter.delete("/delete", (req, res, next) => {
  var oid = req.query.oid;
  if (oid == undefined || oid == "") {
    res.send({ code: 202, msg: "oid不可为空" });
    return;
  }
  var sql = "delete from `order` where oid=?";
  pool.query(sql, [oid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r.affectedRows) {
      res.send({ code: 201, msg: "删除失败" });
    } else {
      res.send({ code: 200, msg: "删除成功" });
    }
  });
});
// 修改订单状态
orderRouter.put("/updateState", (req, res, next) => {
  var oid = req.body.oid;
  var newstate = req.body.newstate;
  if (
    oid == "" ||
    newstate == "" ||
    oid == undefined ||
    newstate == undefined
  ) {
    res.send({ code: 202, msg: "输入不可为空" });
    return;
  }
  var sql = "update `order` set ostate=? where oid=?";
  pool.query(sql, [newstate, oid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.affectedRows) {
      res.send({ code: 200, msg: "修改状态成功" });
    } else {
      res.send({ code: 201, msg: "修改失败" });
    }
  });
});
// 修改地址、收货人和手机号
orderRouter.put("/updateMsg", (req, res, next) => {
  var oid = req.body.oid;
  var oaddress = req.body.oaddress;
  var oname = req.body.oname;
  var ophone = req.body.ophone;
  if (
    oid == "" ||
    oid == undefined ||
    oaddress == "" ||
    oaddress == undefined ||
    oname == "" ||
    oname == undefined ||
    ophone == "" ||
    ophone == undefined
  ) {
    res.send({ code: 202, msg: "输入不可为空" });
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(ophone)) {
    res.send({ code: 203, msg: "手机号格式不正确" });
    return;
  }
  var sql = "update `order` set oaddress=?, oname=?, ophone=? where oid=?";
  pool.query(sql, [oaddress, oname, ophone, oid], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.affectedRows) {
      res.send({ code: 200, msg: "修改成功" });
    } else {
      res.send({ code: 201, msg: "修改失败" });
    }
  });
});
